// pages/order/order.js
const app = getApp()
const util = require('../../utils/util')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    num: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      goods: app.globalData.orderList,
      num: parseInt(options.price),
      name: '',
      phone: '',
      address: ''
    })
    //页面传入的数据是字符串，需要转换一下
    // console.log(new Date())
    // console.log(util.formatTime(new Date))
    // let a = new Date(util.formatTime(new Date)).getTime()
    // console.log(a.toString().slice(0,10))
  },
  //添加地址到订单页面
  addAddress() {
    let that = this
    wx.chooseAddress({
      success: (result) => {
        //console.log(result)
        that.setData({
          phone: result.telNumber,
          name: result.userName,
          address: result.provinceName + result.cityName + result.countyName + result.detailInfo
        })
      },
    })
  },
  //提交订单信息到数据库
  onSubmit() {
    if (this.data.address == '')
      wx.showToast({
        title: '地址信息不完整',
        icon: 'error'
      })
    else{
      this.addData()
    }
  },
  //获取备注记录
  getNote(e) {
    this.setData({
      value: e.detail.value
    })
  },
  //订单信息去重
  updateOrderInfo() {
    //已经提交购买的订单去重
    let b = app.globalData.orderList
    let a = app.globalData.cartList
    let c = app.globalData.checkedList
    let d = app.globalData.goodsNumber
    for (let i = 0; i < b.length; i++) {
      for (let j = 0; j < a.length; j++) {
        if (a[j] === b[i]) {
          a.splice(j, 1)
          c.splice(j, 1)
          d.splice(j, 1)
          j = j - 1;
        }
      }
    }
    app.globalData.cartList = a
    app.globalData.checkedList = c
    app.globalData.goodsNumber = d

    //更新本地存储
    wx.setStorageSync('goodsNumber', app.globalData.goodsNumber)
    wx.setStorageSync('cartList', app.globalData.cartList)
    wx.setStorageSync('checkedList', app.globalData.checkedList)
  },
  //调起支付界面
  pay() {
    let payInfo = null
    app.globalData.rString = this.randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    //let time = (new Date(util.formatTime(new Date)).getTime()).toString().slice(0,10)
    const that = this
    wx.cloud.database().collection('orderInfo').get()
      .then(res => {
        payInfo = res.data
        console.log(payInfo)
        wx.cloud.callFunction({
          // 云函数名称
          name: 'getPayInfo',
          // 传给云函数的参数
          data: {
            _id: payInfo[payInfo.length-1]._id,
            totalFee: this.data.num,
            openid: app.globalData.openid,
            nonceStr: app.globalData.rString
          },
          success: function (res) {
            //console.log(res)
            // 小程序代码
                const payment = res.result.payment
                wx.requestPayment({
                  timeStamp: payment.timeStamp,
                  nonceStr: payment.nonceStr,
                  package: payment.package,
                  signType: 'MD5',
                  paySign: payment.paySign,
                  success(res) {
                    console.log('pay success', res)
                    wx.showToast({
                      title: '支付成功',
                    })
                    wx.cloud.database().collection('orderInfo').doc(payInfo[payInfo.length-1]._id).update({
                      data:{
                           status : 0
                      }
                      }).then(res=>{
                          console.log("数据修改成功");
                      }).catch(res=>{
                          console.log("数据修改失败");
                      })
                    //支付成功后返回
                    setTimeout(() => {
                      wx.navigateBack({
                        delta: 0,
                      })
                    }, 500)
                  },
                  fail(err) {
                    //支付失败后返回
                    wx.showToast({
                      title: '支付失败',
                      icon: 'error'
                    })
                    console.error('pay fail', err)
                    setTimeout(() => {
                      wx.navigateBack({
                        delta: 0,
                      })
                    }, 500)
                  }
                })
          },
          fail: console.error
        })
      })
  },
  //生成32位随机数
  randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
  },
  //添加订单信息到管理平台里
  addData(){
    wx.cloud.database().collection('orderInfo').add({
      data: {
        name: this.data.name,
        phone: this.data.phone,
        address: this.data.address,
        goods: this.data.goods,
        money: this.data.num / 100, //得是浮点数 
        time: util.formatTime(new Date),
        status: -1,//商户订单状态，得改
        notes: this.data.value, //备注信息
        openid: app.globalData.openid,
        track: 0
      }
    }).then(res=>{
      this.pay()
      this.updateOrderInfo()
    })
  }
})